package Bill.app.serveur;


import java.io.*;
import java.net.Socket;
import java.sql.ResultSet;
import java.util.StringTokenizer;

import Bill.app.serveur.bean.Abonnes;
import Bill.app.serveur.bean.Amis;
import Bill.app.serveur.bean.dao.implement.MainDaoImplement;

 
class ThreadAjout extends Thread
{

    ThreadAjout(Socket paquet, String mess)
    {
        this.paquet = null;
        this.paquet = paquet;
        this.mess = mess;
        start();
    }

    public void run()
    {
        PrintWriter ecriture = null;
        try
        {
            ecriture = new PrintWriter(new BufferedWriter(new OutputStreamWriter(paquet.getOutputStream())), true);
        }
        catch(IOException e1)
        {
            e1.printStackTrace();
        }
        StringTokenizer t = new StringTokenizer(mess, ":");
        t.nextToken();
        String t1 = t.nextToken().trim();
        String t2 = t.nextToken().trim();
        String t3 = t.nextToken().trim();
        String t4 = t.nextToken().trim();
        try
        {
            if(ajouterAmi(t2))
            { 
            	
                  try
                {//EntityManager em=new EntityManager();
                	  MainDaoImplement em = SERVEUR.getEm();
            	Abonnes ab = em.loadAbonneByLogin(t1);
            	Abonnes ab1 = em.loadAbonneByLogin(t2);
           	 Amis am1 = new Amis(),am2 = new Amis();
           	 am1.setAbonne(ab);
           	 am1.setAmis(ab1);
           	am2.setAbonne(ab1);
          	 am2.setAmis(ab);
          	 
           	 
           	 em.save(am1);
           	 em.save(am2);
           	 ecriture.println((new StringBuilder("votre contact ")).append(t2).append("a \351t\351 ajout\351 avec succ\350s.").toString());
                }
                catch(Throwable e)
                {
                    mess = "0:erreur d'ajout!";
                    ecriture.println(mess);
                }
            } else
            {
                mess = (new StringBuilder("0: ce contact  ")).append(t2).append(" n'existe pas.").toString();
                ecriture.println(mess);
            }
        }
        catch(Throwable e)
        {
            e.printStackTrace();
        }
        Thread.yield();
        ecriture.close();
    }

    public static boolean ajouterAmi(String t1)
        throws Throwable
    {
    	 return ( SERVEUR.getEm()).loadAbonneByLogin(t1)!=null;
    }

    Socket paquet;
    String mess;
}
